//全局axios请求配合
import { Loading, Message } from 'element-ui';
let options = { lock: true, text: '加载中', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)' },
    loadingPage
export default function({ $axios, redirect }) {
    let axios = $axios;
    axios.defaults.timeout = 10000
    axios.defaults.headers.get['Content-Type'] = 'application/x-www-form-urlencoded'
    axios.defaults.headers.post['Content-Type'] = '	multipart/form-data'
    //localStorage.setItem('token',result.data)
    //localStorage.setItem('userInfo',JSON.stringify(userInfo))
    // 请求回调
    axios.onRequest(config => {
        const jwtToken = 'sdnjkdsjklsdnklsdfkljkljs' || localStorage.getItem("token")
        if (jwtToken) {
            config.headers.Authorization = `${jwtToken}`
        }
        loadingPage = Loading.service(options);
        return config
    })

    // 返回回调
    axios.onResponse(res => {
        if (res.data.code === 2) { // 返回的code（状态码）是2时，证明当前用户需要重新登录
            localStorage.removeItem("username")
            redirect('/login')
        }
        if (res.error) {
            this.$message.error(res.error)
        }
        loadingPage.close()
        return res
    })

    // 错误回调
    axios.onError(error => {
        const code = parseInt(error.response && error.response.status)
        if (code === 401) {
            redirect('/login')
        } else if (code === 400) {
            redirect('/400')
        } else if (code === 500) {
            redirect('/500')
        } else {
            Message.error('接口异常报错')
        }
        loadingPage.close()
        return Promise.reject(error)
    })
}